import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-05-31
 * Time: 14:28
 */
public class Test {
    public static void main(String[] args) throws SQLException {
        // 1. 创建数据源
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/jdbctest?characterEncoding=utf8&useSSL=false");
        dataSource.setUser("root");//账号
        dataSource.setPassword("111111");//密码
        // 2. 建立连接
        Connection connection = dataSource.getConnection();
        // 3. 构建 sql
        String sql = "select * from student";
        PreparedStatement statement = connection.prepareStatement(sql);
        // 4. 执行 sql
        ResultSet resultSet = statement.executeQuery();//返回值是ResultSet,可以理解为数据集合
        // 5. 遍历结果集合
        while (resultSet.next()) {
            // 循环里针对一行进行处理
            System.out.println(resultSet.getInt("id") + "\t" + resultSet.getString("name"));
        }
        // 6. 关闭对应的资源
        resultSet.close();
        statement.close();
        connection.close();
    }

    public static void main1(String[] args) throws SQLException {
        // 1. 创建数据源
        MysqlDataSource dataSource = new MysqlDataSource();
        dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/jdbctest?characterEncoding=utf8&useSSL=false");
        dataSource.setUser("root");//账号
        dataSource.setPassword("111111");//密码
        // 2. 建立连接
        Connection connection = dataSource.getConnection();
        // 3. 构建 sql
        String sql = "insert into student values(?,?)";
        PreparedStatement statement = connection.prepareStatement(sql);
        //3.1 在控制台输入要插入的值
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入学生id");
        int id = scanner.nextInt();
        System.out.println("请输入学生姓名");
        String name = scanner.next();
        statement.setInt(1, id);//1表示下标,从1开始!!,id表示列
        statement.setString(2, name);
        // 4. 执行 sql
        int n = statement.executeUpdate();
        System.out.println(n + "行受到影响");
        // 5. 关闭对应的资源
        statement.close();
        connection.close();
    }
}
